# Copyright (c) 2024, cy080585@126.com and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document


class Payment(Document):

    def before_save(self):
        if self.customer and self.payment_amount:
            self.unpaid_amount=get_unpaid_amount(self.customer)
            if self.payment_amount>self.unpaid_amount:
                frappe.throw(_("Payment Amount cannot be greater than Unpaid Amount"))
            items=frappe.get_all("Packing Process", filters={"customer": self.customer,"is_settled":0,"docstatus":1}, 
                                 fields=["name as packing_process_no","posting_date as packing_process_date","invoice_no","order_total_amount as amount","total_amount_paid"]
                                ,order_by='posting_date')
            payment_amount=self.payment_amount
            for item in items:
                item["unpaid_amount"]=item.amount-item.total_amount_paid
                if item.unpaid_amount>=payment_amount:
                    item["payment_amount"]=payment_amount
                    break
                else:
                    item["payment_amount"]=item.unpaid_amount
                    payment_amount-=item.unpaid_amount
            items=[item for item in items if item.payment_amount]
            self.set("items",items)
        
    
    def after_save(self):
        self.reload()
    
    def on_submit(self):
        for item in self.items:
            updatevalues={
                "total_amount_paid":item.payment_amount+item.total_amount_paid,
                "is_settled":1 if item.payment_amount+item.total_amount_paid>=item.amount else 0
            }
            frappe.db.set_value("Packing Process",item.packing_process_no,updatevalues)


    def on_cancel(self):
        for item in self.items:
            updatevalues={
                "total_amount_paid":item.total_amount_paid,
                "is_settled":1 if item.total_amount_paid>=item.amount else 0
            }
            frappe.db.set_value("Packing Process",item.packing_process_no,updatevalues)


@frappe.whitelist()
def get_unpaid_amount(customer):
    res = frappe.db.get_all("Packing Process", filters={"customer": customer,"is_settled":0,"docstatus":1}, fields=["sum(order_total_amount) as order_total_amount","sum(total_amount_paid) as total_amount_paid"])
    return res[0].get("order_total_amount",0) or 0.00 - (res[0].get("total_amount_paid",0) or 0.00)

